// pages/capsule/new-diary.js

const api = require('../../services/api')
const storage = require('../../utils/storage')

Page({
  data: {
    // 心情数据
    moods: [
      {
        id: 'joy',
        text: '喜悦',
        color: '#FFD93D',
        bgColor: 'linear-gradient(135deg, #FFD93D, #FF8C42)',
        icon: '/images/default-cover.png',
        description: '闪闪发光的一天',
        intensity: 0.8,
        tags: ['开心', '想要分享', '这就是幸福']
      },
      {
        id: 'peace',
        text: '平静',
        color: '#6BCF7F',
        bgColor: 'linear-gradient(135deg, #6BCF7F, #43A047)',
        icon: '/images/default-cover.png',
        description: '安心的宁静时光',
        intensity: 0.6,
        tags: ['舒服', '温暖', '岁月静好']
      },
      {
        id: 'touched',
        text: '感动',
        color: '#E91E63',
        bgColor: 'linear-gradient(135deg, #E91E63, #F50057)',
        icon: '/images/default-cover.png',
        description: '心里暖暖的瞬间',
        intensity: 0.9,
        tags: ['好温柔', '想哭', '被爱到了']
      },
      {
        id: 'nostalgic',
        text: '怀念',
        color: '#9C27B0',
        bgColor: 'linear-gradient(135deg, #9C27B0, #673AB7)',
        icon: '/images/default-cover.png',
        description: '那些美好时光',
        intensity: 0.7,
        tags: ['回忆', '时光很美', '想念某人']
      },
      {
        id: 'anxious',
        text: '焦虑',
        color: '#FF5252',
        bgColor: 'linear-gradient(135deg, #FF5252, #D32F2F)',
        icon: '/images/default-cover.png',
        description: '不安的小烦恼',
        intensity: 0.5,
        tags: ['压力大', '担心', '需要抱抱']
      },
      {
        id: 'consoling',
        text: '安抚',
        color: '#3F51B5',
        bgColor: 'linear-gradient(135deg, #3F51B5, #1976D2)',
        icon: '/images/default-cover.png',
        description: '没事了没事了',
        intensity: 0.4,
        tags: ['自我安慰', '一切都会好', '世界上还有我']
      }
    ],
    selectedMood: null,
    diaryContent: '',
    mediaList: [],
    emotionTags: [],
    currentLocation: '',
    currentWeather: '',
    currentTime: '',
    futureDate: '',
    timeSelection: 'now',
    isSaving: false,
    showColorTuner: false
  },

  onLoad(options) {
    this.setCurrentTime()
    this.getLocationAndWeather()
    this.loadEmotionTags()
  },

  onShow() {
    this.startMoodAnimation()
  },

  // 设置当前时间
  setCurrentTime() {
    const now = new Date()
    const timeString = now.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit'
    })
    const dateString = now.toLocaleDateString('zh-CN', {
      month: 'long',
      day: 'numeric',
      weekday: 'long'
    })
    this.setData({
      currentTime: `${dateString} ${timeString}`
    })
  },

  // 获取位置天气
  async getLocationAndWeather() {
    try {
      // 模拟位置获取
      this.setData({
        currentLocation: '温柔的小角落',
        currentWeather: '心情刚好'
      })
    } catch (error) {
      console.log('获取位置天气失败')
    }
  },

  // 加载情感标签
  loadEmotionTags() {
    const emotionTags = [
      '温暖的回忆', '想哭的瞬间', '被温柔以待', '值得记住', 
      '心情不好', '需要安慰', '心里很安静', '这就是幸福',
      '不完美也很美', '紧张中带着期待', '被理解的感觉', '偷偷乐在其中'
    ].map(name => ({ name, selected: false }))
    
    this.setData({ emotionTags })
  },

  // 心情选择
  selectMood(e) {
    const mood = e.currentTarget.dataset.item
    this.setData({ 
      selectedMood: mood,
      showColorTuner: true
    })
    this.updateMoodBackground(mood)
  },

  // 更新心情背景
  updateMoodBackground(mood) {
    this.setData({
      moodBackground: mood.bgColor,
      moodIntensity: mood.intensity * 100
    })
  },

  // 心情动画
  startMoodAnimation() {
    setInterval(() => {
      if (this.data.selectedMood) {
        const newIntensity = 0.8 + Math.sin(Date.now() * 0.001) * 0.2
        this.setData({
          moodIntensity: newIntensity * this.data.selectedMood.intensity * 100
        })
      }
    }, 100)
  },

  // 日记内容变化
  onDiaryInput(e) {
    const content = e.detail.value
    this.setData({ diaryContent: content })
    
    // 自动分析情感
    if (content.length > 10) {
      this.analyzeEmotion(content)
    }
  },

  // 情感分析（模拟）
  analyzeEmotion(content) {
    // 基于关键词的简化情感分析
    const keywords = {
      '开心快乐': 'joy', 
      '害怕担心': 'anxious',
      '温暖感动': 'touched',
      '回忆怀念': 'nostalgic',
      '安慰鼓励': 'consoling',
      '平静放松': 'peace'
    }
    
    const foundMood = Object.keys(keywords).find(key => content.includes(key))
    if (foundMood) {
      const mood = this.data.moods.find(m => m.id === keywords[foundMood])
      if (mood && !this.data.selectedMood) {
        this.setData({
          selectedMood: mood
        })
        this.updateMoodBackground(mood)
      }
    }
  },

  // 添加媒体
  selectImage() {
    wx.chooseImage({
      count: 9,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const newImages = res.tempFiles.map((file, index) => ({
          id: `img_${Date.now()}_${index}`,
          type: 'image',
          url: file.tempFilePath,
          size: file.size
        }))
        
        this.setData({
          mediaList: [...this.data.mediaList, ...newImages]
        })
      }
    })
  },

  recordVoice() {
    wx.startRecord()
  },

  // 情感标签切换
  toggleTag(e) {
    const tag = e.currentTarget.dataset.tag
    const tags = this.data.emotionTags.map(t => 
      t.name === tag.name ? { ...t, selected: !t.selected } : t
    )
    this.setData({ emotionTags: tags })
  },

  // 时间选择
  selectFutureDate(e) {
    this.setData({
      futureDate: e.detail.value,
      timeSelection: 'future'
    })
  },


  // 保存条目
  async saveEntry() {
    if (this.data.isSaving) return
    
    const { selectedMood, diaryContent, mediaList, emotionTags, timeSelection, futureDate } = this.data
    
    if (!selectedMood) {
      wx.showToast({
        title: '先选个心情吧',
        icon: 'none'
      })
      return
    }
    
    if (!diaryContent.trim()) {
      wx.showToast({
        title: '写下你的感受',
        icon: 'none'
      })
      return
    }

    this.setData({ isSaving: true })
    
    try {
      // 模拟保存
      await this.createCapsuleEntry({
        content: diaryContent,
        mood: selectedMood.id,
        moodIntensity: selectedMood.intensity,
        environment: {
          location: this.data.currentLocation,
          weather: this.data.currentWeather,
          time: this.data.currentTime
        },
        tags: emotionTags.filter(t => t.selected).map(t => t.name),
        media: mediaList,
        openType: timeSelection,
        openDate: timeSelection === 'future' ? futureDate : null
      })

      // 动画效果
      setTimeout(() => {
        this.setData({ isSaving: false })
        
        // 成功提示
        wx.showToast({
          title: '记忆已封存 ✨',
          icon: 'success',
          duration: 2000
        })

        // 延迟跳转
        setTimeout(() => {
          wx.navigateBack()
        }, 2000)
      }, 1500)

    } catch (error) {
      console.error('保存失败:', error)
      this.setData({ isSaving: false })
      wx.showToast({
        title: '保存失败，请重试',
        icon: 'error'
      })
    }
  },

  async createCapsuleEntry(data) {
    // 这里调用后端API保存数据
    return new Promise((resolve) => {
      setTimeout(resolve, 1500)
    })
  }
})